const { ListNode, LinkedList } = require('../2. 链表/1. 链表基础/1. 建立线性链表.js')
// 给定两个非空的链表l1和l2，分别表示两个非负整数，每位数字都是按照逆序的方式存储的，每个节点存储一位数字
// 要求计算两个非负整数的和，并逆序返回表示和的链表

// 思路，模拟大数相加法，按位相加，注意进位和取余

function addTwoNumbers(l1, l2) {
    let dummyHead = new ListNode(0)
    let carry = 0
    let cur = dummyHead
    while (l1 || l2 || carry) {
        let sum = 0
        let num1 = 0
        let num2 = 0
        if (l1) {
            num1 = l1.val
            l1 = l1.next
        }
        if (l2) {
            num2 = l2.val
            l2 = l2.next
        }

        sum = num1 + num2 + carry
        console.log(num1, num2, carry)
        carry = Math.floor(sum / 10)
        cur.next = new ListNode(sum % 10)
        cur = cur.next
    }
    return dummyHead.next
}

let l1 = new LinkedList([2,4,3,6]).head
let l2 = new LinkedList([5,6,4]).head
// 6342 + 465 = 6807
let result = addTwoNumbers(l1, l2)
console.log(result)
